<template>
  <basic-container>
    <avue-crud
      :option="option"
      :table-loading="loading"
      :data="data"
      :page.sync="page"
      :permission="permissionList"
      :before-open="beforeOpen"
      v-model="form"
      ref="crud"
      @row-update="rowUpdate"
      @row-save="rowSave"
      @row-del="rowDel"
      @search-change="searchChange"
      @search-reset="searchReset"
      @selection-change="selectionChange"
      @current-change="currentChange"
      @size-change="sizeChange"
      @refresh-change="refreshChange"
      @on-load="onLoad"
    >
      <template slot="menuRight">
        <user-table-config :option="option" @confirm="(val) => handleSetUserConfig(val, pageCode)"></user-table-config>
      </template>
      <template slot="menuLeft">
        <div style="display: flex">
          <el-button
            v-if="isShowInspection && permission.receiving_inspection"
            type="primary"
            size="small"
            icon="el-icon-view"
            :disabled="ids.length > 0 ? false : true"
            @click="submitInspection"
            >送 检</el-button
          >
          <el-button type="primary" size="small" icon="el-icon-view" :disabled="ids.length > 0 ? false : true" v-if="permission.receiving_revoke" @click="cancelEvent()">
            撤 销</el-button
          >
          <el-button type="warning" size="small" icon="el-icon-download" @click="$refs.exportComp.visible = true">导出</el-button>
        </div>
      </template>
      <template slot-scope="{ row }" slot="menu">
        <el-button icon="el-icon-view" size="small" type="text" @click="rowView(row)" v-if="permission.receiving_view"> 查看包装</el-button>
      </template>
    </avue-crud>
    <el-dialog ref="dialog" title="查看包装" class="lookPackDialog" append-to-body :visible.sync="showDialog" :close-on-click-modal="false">
      <avue-crud :option="detailOption" :table-loading="detailLoading" :data="detailData" ref="crud" @on-load="onDetailLoad">
        <template slot-scope="{ row }" slot="sequenceNumber">
          <span style="white-space: pre-wrap">{{ row.sequenceNumber }}</span>
        </template>
      </avue-crud>
    </el-dialog>
    <export-comp ref="exportComp" page-api-url="mes-warehouse/receiving/page" :option="option" :page="page" :query="query" file-name="收料记录"> </export-comp>
  </basic-container>
</template>

<script>
import { getList, getDetail, sendInspection, cancelReceive } from '@/api/warehouse/receiving';
import { getParamDetail } from '@/api/system/param';
import { mapGetters } from 'vuex';
import exportComp from '@/components/export-comp/index';
import CommonModalTemplate from '@/components/common-modal-template/common-modal-template';
import userTableConfig from '@/components/user-table-config/index.vue';
import userConfig from '@/mixins/userConfig';
export default {
  components: {
    exportComp,
    userTableConfig
  },
  mixins: [userConfig()],
  data() {
    return {
      pageCode: 'RECEIVING',
      isShowInspection: true, //检查是否配置系统配置，自动送检及不展示送检按钮
      form: {},
      query: {},
      loading: true,
      page: {
        pageSize: 20,
        currentPage: 1,
        total: 0
      },
      selectionList: [],
      option: {
        height: 'calc(100vh - 485px)',
        calcHeight: 30,
        tip: false,
        searchShow: true,
        searchMenuSpan: 4,
        searchMenuPosition: 'right',
        border: true,
        index: true,
        indexLabel: '序号',
        selection: true,
        dialogClickModal: false,
        searchLabelWidth: 100,
        searchSpan: 6,
        addBtn: false,
        editBtn: false,
        viewBtn: false,
        delBtn: false,
        menuWidth: 100,
        columnBtn: false,
        column: [
          // {
          //   label: '单据类型',
          //   prop: 'receiveType',
          //   type: 'select',
          //   search: true,
          //   searchOrder: 1,
          //   // dicUrl: '/api/blade-system/dict/dictionary?code=sheet_type',
          //   dicData: [
          //     {
          //       label: '采购单收料',
          //       value: 'PO'
          //     },
          //     {
          //       label: '其他收料',
          //       value: 'OTHER'
          //     }
          //   ]
          //   // props: {
          //   //   label: 'dictValue',
          //   //   value: 'dictKey'
          //   // }
          // },
          {
            label: '单据号',
            prop: 'sheetNo',
            width: 150,
            search: true,
            searchOrder: 2
          },
          {
            label: '单据类型',
            prop: 'sheetSubType',
            type: 'select',
            dicData: [
              {
                label: '普通采购单',
                value: 'GENERAL'
              },
              {
                label: '委外采购单',
                value: 'OUTSOURCING'
              }
            ]
          },
          {
            label: '收料类型',
            prop: 'receiveType',
            type: 'select',
            search: true,
            width: 150,
            searchOrder: 3,
            dicData: [
              {
                label: '有条码收料',
                value: 'SEQ'
              },
              {
                label: '无条码收料',
                value: 'NO_SEQ'
              },
              {
                label: '其他收料',
                value: 'OTHER'
              },
              {
                label: '有条码委外收料',
                value: 'OUTSOURCE'
              },
              {
                label: '无条码委外收料',
                value: 'NO_SEQ_OUTSOURCE'
              },
              {
                label: '供应商批量收',
                value: 'SUPPLIER_BATCH'
              },
              {
                label: '单个采购单收料',
                value: 'SINGLE_PURCHASE_ORDER'
              },
              {
                label: '批量采购单收料',
                value: 'PURCHASE_ORDER_BATCH'
              },
              {
                label: '送货单收料',
                value: 'DELIVER_ORDER'
              }
            ]
          },
          {
            label: '供应商名称',
            prop: 'vendorName',
            width: 150
          },
          // {
          //   label: '单行号',
          //   prop: 'sheetLot'
          // },
          {
            label: '物料编码',
            prop: 'partNo',
            width: 150,
            search: true,
            searchOrder: 4
          },
          {
            label: '物料名称',
            prop: 'partName',
            width: 150,
            search: true,
            searchOrder: 5
          },
          {
            label: '物料规格',
            prop: 'partModel'
          },
          {
            label: '收货数量',
            prop: 'receiveQuantity',
            type: 'number',
            precision: 10
          },
          {
            label: '检验方式',
            prop: 'inspectionMode',
            dicUrl: '/api/blade-system/dict/dictionary?code=inspection_mode',
            props: {
              label: 'dictValue',
              value: 'dictKey'
            }
          },
          // {
          //   label: '送检单号',
          //   prop: 'documentNo'
          // },
          {
            label: '状态',
            prop: 'status',
            search: true,
            type: 'select',
            dicData: [
              {
                label: '待送检',
                value: 1
              },
              {
                label: '待检验',
                value: 2
              },
              {
                label: '待入库',
                value: 3
              },
              {
                label: '已入库',
                value: 4
              },
              {
                label: '已退货',
                value: 5
              },
              {
                label: '已撤销',
                value: 7
              },
              {
                label: '已检验',
                value: 8
              },
              {
                label: '入库中',
                value: 9
              }
            ]
            // formatter: (val, value, label) => {
            //   console.log(val, 66655)
            //   if (val.inspectionMode === 'EXEMPTION') {
            //     switch(val.status){
            //       case 3:
            //         return '待入库';
            //       case 4:
            //         return '已入库';
            //     }
            //   } else {
            //     return label;
            //   }
            // }
          },
          // {
          //   label: '入库数量',
          //   prop: 'inboundQuantity'
          // },
          // {
          //   label: '供应商编码',
          //   prop: 'vendorCode',
          //   search: true,
          //   searchOrder: 3
          // },

          // {
          //   label: '供应商批次',
          //   prop: 'vendorLotNo'
          // },
          {
            label: '检验结果',
            prop: 'examineResult',
            dicData: [
              {
                label: '合格',
                value: 'OK'
              },
              {
                label: '不合格',
                value: 'NG'
              }
            ]
          },
          {
            label: '实收数量',
            prop: 'actuallyReceive',
            type: 'number',
            precision: 10
          },
          {
            label: '收料人',
            prop: 'receiveBy'
          },
          {
            label: '收料时间',
            width: 130,
            prop: 'receiveDate',
            search: true,
            searchSpan: 8,
            type: 'date',
            searchType: 'datetimerange',
            format: 'yyyy-MM-dd HH:mm:ss',
            valueFormat: 'yyyy-MM-dd HH:mm:ss',
            startPlaceholder: '开始日期',
            endPlaceholder: '结束日期'
          },
          {
            label: '生产时间',
            width: 130,
            prop: 'vendorDate'
          },
          {
            label: '备注',
            prop: 'remark'
          }
        ]
      },
      data: [],
      showDialog: false, //查看详情模态框是否显示
      detailLoading: false,
      detailData: [], //收料详情数据
      detailOption: {
        height: 'calc(100vh - 350px)',
        calcHeight: 30,
        tip: false,
        border: true,
        index: true,
        selection: false,
        dialogClickModal: false,
        addBtn: false,
        editBtn: false,
        viewBtn: false,
        delBtn: false,
        menu: false,
        refreshBtn: false,
        columnBtn: false,
        column: [
          {
            label: '包装条码',
            prop: 'sequenceNumber',
            solt: true
          },
          {
            label: '数量',
            prop: 'quantity'
          },
          {
            label: '是否尾箱',
            prop: 'isTailBox',
            dicData: [
              {
                label: '否',
                value: false
              },
              {
                label: '是',
                value: true
              }
            ]
          },
          {
            label: '状态',
            prop: 'packStatus',
            type: 'select',
            dicUrl: '/api/blade-system/dict/dictionary?code=pack_status',
            props: {
              label: 'dictValue',
              value: 'dictKey'
            }
          },
          {
            label: '外部条码',
            prop: 'externalSequenceNumber',
            display: false
          }
        ]
      } //收料详情表格配置
    };
  },
  computed: {
    ...mapGetters(['permission']),
    permissionList() {
      return {
        viewBtn: this.vaildData(this.permission.receiving_view, false)
      };
    },
    ids() {
      let ids = [];
      this.selectionList.forEach((ele) => {
        ids.push(ele.id);
      });
      return ids.join(',');
    }
  },
  methods: {
    searchReset() {
      this.query = {};
      this.onLoad(this.page);
    },
    searchChange(params, done) {
      if (params.receiveDate && params.receiveDate.length > 0) {
        params.startTime = params.receiveDate[0];
        params.endTime = params.receiveDate[1];
        // this.$moment(this.$moment(params.receiveDate[1]).add(1, 'days')).format('YYYY-MM-DD');
        delete params.receiveDate;
      }
      this.query = params;
      this.page.currentPage = 1;
      this.onLoad(this.page);
      done();
    },
    selectionChange(list) {
      this.selectionList = list;
    },
    selectionClear() {
      this.selectionList = [];
      this.$refs.crud.toggleSelection();
    },
    currentChange(currentPage) {
      this.page.currentPage = currentPage;
    },
    sizeChange(pageSize) {
      this.page.pageSize = pageSize;
    },
    refreshChange() {
      this.onLoad(this.page, this.query);
    },
    onLoad(page, params = {}) {
      this.loading = true;
      getList(page.currentPage, page.pageSize, Object.assign(params, this.query)).then((res) => {
        const data = res.data.data;
        this.page.total = data.total;
        this.data = data.records;
        this.loading = false;
        this.selectionClear();
      });
    },
    rowView(row) {
      let column = this.findObject(this.detailOption.column, 'externalSequenceNumber');
      if (row.sheetSubType === 'GENERAL') {
        column.hide = true;
      } else {
        column.hide = false;
      }
      this.showDialog = true;
      this.detailLoading = true;
      getDetail(row.id).then((res) => {
        this.detailData = res.data.data;
        console.log();
        for (let i = 0; i < this.detailData.length; i++) {
          console.log(this.detailData[0].sequenceNumber, 88877);
          this.detailData[i].packStatus = String(this.detailData[i].packStatus);
        }
        this.detailLoading = false;
      });
    },
    /*
     *撤销
     */
    cancelEvent() {
      this.$confirm('是否撤销所选物料的收料记录?', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(() => {
          return cancelReceive(this.ids)
            .then((res) => {
              this.$message({
                type: 'success',
                message: '撤销成功!'
              });
            })
            .catch((err) => {
              // this.$message.error('撤销失败');
            });
        })
        .then(() => {
          this.onLoad(this.page);
          this.$refs.crud.toggleSelection();
        });
    },
    submitInspection() {
      let ids = [];
      this.selectionList.forEach((ele) => {
        ids.push(ele.id);
      });
      let params = {
        receivingId: ids
      };
      sendInspection(params).then((res) => {
        if (res.data.code === 200) {
          this.$message({
            type: 'success',
            message: res.data.msg
          });
          this.inspectionDialog = false;
          this.refreshChange();
        }
      });
    },
    //获取系统是否配置自动送检功能，若配置并且启用则不需展示送检按钮
    getInspectionParamDetail(params) {
      getParamDetail(params).then((res) => {
        if (res.data.code === 200) {
          if (res.data.data && res.data.data.paramValue == 'true') {
            this.isShowInspection = false;
          }
        }
      });
    }
  },
  mounted() {
    this.getInspectionParamDetail({ paramKey: 'inventory.receiving.autoInspection' });
    this.$nextTick(() => {
      this.$structuralSplit();
    });
  }
};
</script>

<style lang="scss" scoped>
.lookPackDialog {
  ::v-deep.avue-crud__menu {
    display: none;
  }
}
::v-deep .el-dialog__header {
  padding: 16px 24px;
  min-height: 20px;
  border-bottom: 1px solid #f0f0f0;
}
</style>
